package com.htime.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * Created by HTime on 2017/3/5.
 */
public class GsonUtil {

    static private Gson _gson ;

    static public class UtilDateSerialization implements JsonSerializer<Date>
    {
        public JsonElement serialize(Date src, Type typeOfSrc,
                                     JsonSerializationContext context) {

            return new JsonPrimitive(src.getTime());
        }

    }
    static  public class UtilDateDeserialization implements JsonDeserializer<Date> {

        public Date deserialize(JsonElement json, Type typeOfT,
                                JsonDeserializationContext context) throws JsonParseException {
            return new java.util.Date(json.getAsLong());
        }

    }

    static public Gson createGson( ) {

        if( _gson ==null ) {

            GsonBuilder builder = new GsonBuilder()
                    .registerTypeAdapter(java.util.Date.class ,new UtilDateSerialization()  )
                    .registerTypeAdapter(java.util.Date.class ,new UtilDateDeserialization()  )
                    ;
            _gson= builder.create() ;

        }

        return _gson ;
    }

}
